package com.newgrand.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.newgrand.mapper.*;
import com.newgrand.model.*;
import com.newgrand.utils.DateUtil;
import com.newgrand.utils.i8util.EntityConverter;
import com.newgrand.utils.i8util.HttpHelper;
import com.newgrand.utils.i8util.I8Request;
import com.newgrand.utils.i8util.StringHelper;
import com.newgrand.utils.security.Md5Utils;
import com.newgrand.utils.uuid.GetNewPhidUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: zhanglixin
 * @Data: 2022/11/24 19:38
 * @Description: TODO
 */
@Service
public class SupplyService {

    @Autowired
    private CPfcBillnoRuleMMapper cPfcBillnoRuleMMapper;

    @Autowired
    private I8Request i8Request;
    @Autowired
    private UipLog uipLog;
    @Autowired
    private UIPCommonMapper uipCommonMapper;
    @Autowired
    private EntityConverter entityConverter;

    private static final String entpriseformData = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"CompNo\":\"\",\"CompName\":\"\",\"PersonFlg\":0,\"SimpName\":\"\",\"SimpName2\":\"\",\"HelpCode\":\"\",\"OldName\":\"\",\"UnisocialCredit\":\"\",\"TaxNo\":\"\",\"CardType\":\"\",\"CardNo\":\"\",\"NationId\":1,\"ProvinceId\":\"\",\"CityId\":\"\",\"RegionId\":0,\"TradeTypeId\":\"\",\"ParentCompId\":\"\",\"NgShareSign_tmp\":\"1\",\"IcChangeDt\":\"\",\"Remarks\":\"\",\"GroupShareFlg_tmp\":\"0\",\"PhId\":\"\",\"AuditFlg\":\"\",\"AuditDt\":\"\",\"AuditPsnId\":\"\",\"EstablishDate\":\"\",\"TaxPayerType\":\"\",\"TaxPayerName\":\"\",\"TaxBankId\":\"\",\"TaxBankName\":\"\",\"TaxAccountNo\":\"\",\"TaxAddress\":\"\",\"TaxTelePhone\":\"\",\"RegMoney\":\"\",\"RegDt\":\"\",\"RegScope\":\"\",\"Person\":\"\",\"TradeGradeId\":\"\",\"EnterNatureId\":\"\",\"ScaleId\":\"\",\"Url\":\"\",\"Email\":\"\",\"IsTemp\":\"0\",\"IsInner\":\"0\",\"IsBlackList_tmp\":\"0\",\"GroupShareFlg\":\"1\",\"key\":\"\"}}}";
    private static final String supplyfileformData = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"FsaleFlg\":1,\"SupplyRankId\":\"0\",\"DeptId\":\"\",\"EmpId\":\"\",\"OrgId\":\"\",\"Creator\":\"\",\"NgInsertDt\":\"\",\"AuditFlg\":\"\",\"Accstop\":\"\",\"AccstopBDt\":\"\",\"AccstopEndDt\":\"\",\"GfiCboo\":\"\",\"BpIds\":\"\",\"BidFlag\":\"\",\"EntId\":\"\",\"SuppClassId\":\"1000\",\"AuditPsnId\":\"\",\"AuditDt\":\"\",\"PhIdScheme\":\"\",\"ImpInfo\":\"\",\"ResourceTable\":\"\",\"PhIdResource\":\"\",\"PhId\":\"\",\"NgRecordVer\":\"\",\"GroupShareFlg\":\"1\",\"NgShareSign\":\"1\",\"IsBlackList\":\"0\",\"ListFilterVal\":\"\",\"QueryField1Val\":\"\",\"QueryField2Val\":\"\",\"UIMultiConfigID\":\"\",\"key\":\"\"}}}";

    private static final String addressgridData = "{\"table\":{\"key\":\"PhId\"}}";
    private static final String linkmangridData = "{\"table\":{\"key\":\"PhId\"}}";
    private static final String suppCategoryGridData ="{\"table\":{\"key\":\"PhId\",\"newRow\":[{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"1000\",\"CategoryNo\":\"1\",\"CategoryName\":\"无类型\",\"SelectedMain\":true,\"Selected\":true,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"12\",\"CategoryNo\":\"01000102\",\"CategoryName\":\"劳务分包商\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"11\",\"CategoryNo\":\"01000101\",\"CategoryName\":\"专业分包商\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"10\",\"CategoryNo\":\"010009\",\"CategoryName\":\"劳务负责人\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"9\",\"CategoryNo\":\"010008\",\"CategoryName\":\"服务供应商\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"8\",\"CategoryNo\":\"019999\",\"CategoryName\":\"物流公司\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"7\",\"CategoryNo\":\"010007\",\"CategoryName\":\"设备供应商\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"6\",\"CategoryNo\":\"010006\",\"CategoryName\":\"其他供应商\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"5\",\"CategoryNo\":\"010005\",\"CategoryName\":\"材料供应商\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"4\",\"CategoryNo\":\"010004\",\"CategoryName\":\"监理单位\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"3\",\"CategoryNo\":\"010003\",\"CategoryName\":\"设计院\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"2\",\"CategoryNo\":\"010002\",\"CategoryName\":\"运输单位\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}},{\"row\":{\"PhId\":\"0\",\"EntId\":\"0\",\"OrgId\":\"0\",\"CategoryId\":\"1\",\"CategoryNo\":\"010001\",\"CategoryName\":\"分包商\",\"SelectedMain\":false,\"Selected\":false,\"Creator\":\"0\",\"Editor\":\"0\",\"NgInsertDt\":\"2022-11-24 19:43:58\",\"NgUpdateDt\":\"2022-11-24 19:43:58\",\"NgRecordVer\":0,\"PhIdSupplyRank\":\"0\",\"PhIdSupplyRank_EXName\":\"\",\"key\":null}}]},\"isChanged\":true}";
    private static final String suppItemGridData ="{\"table\":{\"key\":\"PhId\"}}";
    private static final String cardInfoGridData ="{\"table\":{\"key\":\"PhId\"}}";
    private static final String qualificationGridData ="{\"table\":{\"key\":\"PhId\"}}";
    private static final String supplysettleinfoData ="{\"form\":{\"key\":\"PhId\",\"newRow\":{\"BillToId\":\"\",\"PayWayId\":\"\",\"FcId\":\"1\",\"BankId\":\"\",\"AccountNo\":\"\",\"DiscType\":\"\",\"DiscRate\":\"\",\"AccountName\":\"\",\"ProvinceId\":\"\",\"CityId\":\"\",\"RegionId\":\"\",\"CreditRankId\":\"\",\"CreditDays\":\"\",\"CreditNum\":\"\",\"PayDay\":\"\",\"PayAcctId\":\"\",\"PrepayAcctId\":\"\",\"PurAcctId\":\"\",\"InAcctId\":\"\",\"PhId\":\"\",\"key\":\"\"}}}";
    private static final String supplybusiinfoData ="{\"form\":{\"key\":\"PhId\",\"newRow\":{\"OrderCyc\":\"\",\"DelDay\":\"\",\"BackPeriod\":\"\",\"BackRate\":\"\",\"PhId\":\"\",\"GoodsToId\":\"\",\"ShipTypeId\":\"\",\"SupitemBarCodeStart\":\"\",\"SupitemBarCodeLength\":\"\",\"key\":\"\"}}}";

    private static final String unitaccountData = "{\"table\":{\"key\":\"PhId\"}}";
    private static final String parentcompData = "{\"table\":{\"key\":\"PhId\"}}";
    private static final String suppEvaluateGridData = "{\"table\":{\"key\":\"PhId\"}}";
    private static final String laborSubContractorGridData = "{\"table\":{\"key\":\"PhId\"}}";

    @Value("${oa.url}")
    private String oaUrl;

    @Value("${oa.registerCode}")
    private String oaSystemid;

    @Value("${oa.password}")
    private String oaPassword;

    @Value("${ck.url}")
    private String ckUrl;

    @Autowired
    private Fg3EnterpriseMapper fg3EnterpriseMapper;

    @Autowired
    private FgBankMapper fgBankMapper;

    @Autowired
    private Fg3SupplyfileMapper fg3SupplyfileMapper;

    @Autowired
    private Fg3UnitaccountMapper fg3UnitaccountMapper;
    @Autowired
    private Fg3SupplysettleinfoMapper fg3SupplysettleinfoMapper;

    @Autowired
    private SuppClassMapper suppClassMapper;

    @Autowired
    private SecDevMdmSupplyMapper secDevMdmSupplyMapper;

    @Autowired
    private Fg3SupplyfileCategoryMapper fg3SupplyfileCategoryMapper;

    JSONArray recurrenceSupply(int pageNum,int pageSize){
        String postUrl =ckUrl +"/supplier/supplierInfo/provideList?pageNum="+pageNum+"&pageSize="+pageSize;
        Header[] headers = new Header[]{
                new BasicHeader("Content-Type","application/json")
        };
        String rtnMsg = HttpHelper.Get(postUrl,headers);
        if(!StringUtils.isEmpty(rtnMsg)){
            JSONObject supplyJO = JSONObject.parseObject(rtnMsg);
            if("200".equals(supplyJO.getString("code"))){
                JSONArray rowsJA = supplyJO.getJSONArray("rows");
                if(rowsJA!=null&&rowsJA.size()>0)
                    return rowsJA;
            }
        }
        return null;
    }


    public void SyncData() {

        try {

            //检测是否启用单据编码规则设置  启用了不进行数据同步
            /*
            QueryWrapper<CPfcBillnoRuleM> queryCodeRuleWrapper = new QueryWrapper<>();
            queryCodeRuleWrapper.eq("c_btype","SUPPLY")
                    .eq("codemode","1")
                    .eq("user_mod_flg","1")
                    .eq("sysflg","1");
            Long codeRule = cPfcBillnoRuleMMapper.selectCount(queryCodeRuleWrapper);
            if(codeRule>0){
                throw new Exception("供应商启用了单据编码规则生成,接口不进行同步数据.");
            }
             */

            List<SuppClass> suppClassList = suppClassMapper.selectList(null);

            //查询供应商数据
            JSONArray supplyJA = new JSONArray();
            int pageSize = 1000;
            int pageNum = 1;
            String postUrl =ckUrl +"/supplier/supplierInfo/provideList?pageNum="+pageNum+"&pageSize="+pageSize;
            Header[] headers = new Header[]{
                    new BasicHeader("Content-Type","application/json")
            };
            String rtnMsg = HttpHelper.Get(postUrl,headers);
            if(!StringUtils.isEmpty(rtnMsg)){
                JSONObject supplyJO = JSONObject.parseObject(rtnMsg);
                if("200".equals(supplyJO.getString("code"))){
                    JSONArray rowsJA = supplyJO.getJSONArray("rows");
                    supplyJA.addAll(rowsJA);
                    int total = supplyJO.getIntValue("total");
                    int totalPage = total / pageSize + (total % pageSize == 0 ? 0 : 1);
                    while (pageNum<totalPage){
                        pageNum++;
                        JSONArray currentJA = recurrenceSupply(pageNum,pageSize);
                        if(currentJA!=null&&currentJA.size()>0){
                            supplyJA.addAll(currentJA);
                        }
                    }
                }
            }

            int totalSize = supplyJA.size();
            if(totalSize==0){
                uipLog.info("supplysync", "同步供应商","未获取到供应商的信息");
            }
            uipLog.info("supplysync", "同步供应商","获取到供应商条数:"+totalSize);
            for(int i=0;i<totalSize;i++){
                JSONObject resultJO = supplyJA.getJSONObject(i);
                SyncCkSupplyByDataJO(resultJO,suppClassList);
            }
        }catch (Exception ex){
            uipLog.error("supplysync", "同步供应商","同步异常:"+ex.getMessage());
        }

    }

    public boolean SyncCkSupplyByDataJO(JSONObject resultJO,List<SuppClass> suppClassList){
        boolean flag = false;
        SupplyModel supplyModel = new SupplyModel();

        supplyModel.compname = resultJO.getString("name");
        supplyModel.unisocialcredit = resultJO.getString("certifyNo");
        String taxType = resultJO.getString("taxType");
        JSONArray suplyTypeJA = resultJO.getJSONArray("suplyType");
        int types = suplyTypeJA.size();
        List<String> gystype = new ArrayList<>();
        for(int t=0;t<types;t++){
            String suplyType = suplyTypeJA.getString(t);
            //转换成i8的phid
            //供应商类型维护里面描述字段存了对照关系
            if(!StringUtils.isEmpty(suplyType)){
                List<SuppClass> suppClasses = suppClassList.stream().filter(map->suplyType.equals(map.getDescript())).collect(Collectors.toList());
                if(suppClasses!=null&&suppClasses.size()>0){
                    SuppClass suppClass = suppClasses.get(0);
                    gystype.add(suppClass.getPhid());
                }
            }
        }
        String id = resultJO.getString("id");
        String legalName = resultJO.getString("legalName");
        String identityNo = resultJO.getString("identityNo");
        identityNo = StringUtils.isEmpty(identityNo)?"":identityNo;

        String bank = resultJO.getString("bank");
        bank = StringUtils.isEmpty(bank)?"":bank;
        String bankAccount = resultJO.getString("bankAccount");
        bankAccount = StringUtils.isEmpty(bankAccount)?"":bankAccount;

        supplyModel.person = legalName;
        supplyModel.suppclass = gystype;
        QueryWrapper<Fg3Enterprise> fg3EnterpriseQueryWrapper = new QueryWrapper<>();
        fg3EnterpriseQueryWrapper.eq("unisocialcredit",supplyModel.unisocialcredit);
        List<Fg3Enterprise> fg3EnterpriseList = fg3EnterpriseMapper.selectList(fg3EnterpriseQueryWrapper);
        if(fg3EnterpriseList!=null&&fg3EnterpriseList.size()>0){
            Fg3Enterprise fg3Enterprise = fg3EnterpriseList.get(0);
            supplyModel.compno = fg3Enterprise.getCompno();
            //用i8原先的编码
        }else{
            supplyModel.compno = id;
        }
        List<SupplyBankInfo> bankInfoList = new ArrayList<>();
        SupplyBankInfo supplyBankInfo = new SupplyBankInfo();
        supplyBankInfo.bankno = resultJO.getString("bankno");
        supplyBankInfo.saccount = resultJO.getString("bankAccount");
        supplyBankInfo.accountName = resultJO.getString("name");
        supplyBankInfo.isdef = "1";
        bankInfoList.add(supplyBankInfo);
        supplyModel.bankInfoList = bankInfoList;
        CodeMsg codeMsg = Save(supplyModel);
        String taxpayertype = "一般纳税人".equals(taxType)?"1":"2";
        if("S".equals(codeMsg.code)){
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("unisocialcredit", supplyModel.unisocialcredit);
            updateWrapper.set("user_frcardno",identityNo);
            //updateWrapper.set("user_khyhmc",bank);
            //updateWrapper.set("user_khyhzh",bankAccount);
            updateWrapper.set("user_gysid",id);
            updateWrapper.set("taxpayertype",taxpayertype);
            fg3EnterpriseMapper.update(null,updateWrapper);
            flag = true;
        }
        uipLog.info("supplysync", "同步供应商","compno:"+supplyModel.compno+",名称:"+supplyModel.compname+";供应商类型:"+String.join(",", supplyModel.getSuppclass())+",同步返回:"+JSON.toJSONString(codeMsg));
        return flag;
    }

    public CodeMsg Save(SupplyModel supplyModel) {
        CodeMsg codeMsg = new CodeMsg();
        try
        {
            QueryWrapper<Fg3Enterprise> queryIsExistWrapper = new QueryWrapper<>();
            queryIsExistWrapper.eq("compno",supplyModel.compno);
            List<Fg3Enterprise> fg3EnterpriseList = fg3EnterpriseMapper.selectList(queryIsExistWrapper);
            if(fg3EnterpriseList==null||fg3EnterpriseList.size()==0){
                //执行新增
                List<NameValuePair> urlParameters = new ArrayList<>();
                HashMap<String, Object> mapInfo = new HashMap<String, Object>();
                mapInfo.put("CompNo", supplyModel.compno);//
                mapInfo.put("CompName", supplyModel.compname);
                mapInfo.put("SimpName", supplyModel.simpname);
                mapInfo.put("UnisocialCredit", supplyModel.unisocialcredit);
                mapInfo.put("TaxPayerName", supplyModel.compname);
                mapInfo.put("Person", supplyModel.person);
                urlParameters.add(new BasicNameValuePair("entpriseformData", entityConverter.SetFieldForm(entpriseformData, mapInfo)));

                urlParameters.add(new BasicNameValuePair("supplyfileformData", supplyfileformData));

                urlParameters.add(new BasicNameValuePair("addressgridData", addressgridData));
                urlParameters.add(new BasicNameValuePair("linkmangridData", linkmangridData));
                urlParameters.add(new BasicNameValuePair("suppCategoryGridData", suppCategoryGridData));
                urlParameters.add(new BasicNameValuePair("suppItemGridData", suppItemGridData));
                urlParameters.add(new BasicNameValuePair("cardInfoGridData", cardInfoGridData));
                urlParameters.add(new BasicNameValuePair("qualificationGridData", qualificationGridData));
                urlParameters.add(new BasicNameValuePair("supplysettleinfoData", supplysettleinfoData));
                urlParameters.add(new BasicNameValuePair("supplybusiinfoData", supplybusiinfoData));
                urlParameters.add(new BasicNameValuePair("unitaccountData", unitaccountData));
                urlParameters.add(new BasicNameValuePair("parentcompData", parentcompData));
                urlParameters.add(new BasicNameValuePair("suppEvaluateGridData", suppEvaluateGridData));
                urlParameters.add(new BasicNameValuePair("laborSubContractorGridData", laborSubContractorGridData));
                urlParameters.add(new BasicNameValuePair("busguid", ""));
                urlParameters.add(new BasicNameValuePair("empGridData", "{\"table\":{\"key\":\"PhId\"}}"));
                urlParameters.add(new BasicNameValuePair("puic_changeid", ""));
                urlParameters.add(new BasicNameValuePair("puic_changeresult", ""));
                urlParameters.add(new BasicNameValuePair("puic_changesuggest", ""));
                urlParameters.add(new BasicNameValuePair("refType", ""));
                urlParameters.add(new BasicNameValuePair("refId", "0"));
                urlParameters.add(new BasicNameValuePair("ocrguid", ""));

                String i8rv = i8Request.PostFormSync("/DMC/Enterprise/SupplyFile/save", urlParameters);
                JSONObject i8rvJson = null;
                try{
                    i8rvJson = JSONObject.parseObject(i8rv);
                }catch (Exception ex){
                    codeMsg.code = "E";
                    codeMsg.msg = "保存信息失败:"+i8rv;
                    return codeMsg;
                }
                Date now = new Date();
                if (i8rvJson != null && i8rvJson.getString("Status").toLowerCase().equals("success")) {
                    //["518220916036008", "518190815000004", "329190425000002"]
                    // 供应商phid 往来单位phid  组织phid
                    JSONArray keyJA = i8rvJson.getJSONArray("KeyCodes");
                    String ent_id = "";
                    String org_id = "";
                    if(keyJA.size()==1){
                        //那就只返回一个供应商的phid
                        String phid = keyJA.getString(0);
                        Fg3Supplyfile fg3Supplyfile = fg3SupplyfileMapper.selectById(phid);
                        ent_id = fg3Supplyfile.getEntId();
                        org_id = fg3Supplyfile.getOrgId();
                    }else{
                        ent_id = keyJA.getString(1);
                        org_id = keyJA.getString(2);
                    }
                    UpdateWrapper updateEntWrapper = new UpdateWrapper();
                    updateEntWrapper.eq("phid", ent_id);
                    updateEntWrapper.set("auditflg","1");
                    fg3EnterpriseMapper.update(null,updateEntWrapper);

                    List<String> supplyTypes = supplyModel.getSuppclass();
                    if(supplyTypes!=null&&supplyTypes.size()>0){
                        int types = supplyTypes.size();
                        for(int i=0;i<types;i++){
                            String suppclassId = supplyTypes.get(i);
                            if(i==0){
                                //处理供应商主类型
                                UpdateWrapper updateWrapper = new UpdateWrapper();
                                updateWrapper.eq("ent_id", ent_id);
                                updateWrapper.set("suppclass_id",suppclassId);
                                updateWrapper.set("auditflg","1");
                                fg3SupplyfileMapper.update(null,updateWrapper);
                            }
                            //处理供应商分类的问题
                            QueryWrapper<Fg3SupplyfileCategory> fg3SupplyfileCategoryQueryWrapper = new QueryWrapper<>();
                            fg3SupplyfileCategoryQueryWrapper.eq("ent_id",ent_id).eq("category_id",suppclassId);
                            List<Fg3SupplyfileCategory> fg3SupplyfileCategoryList = fg3SupplyfileCategoryMapper.selectList(fg3SupplyfileCategoryQueryWrapper);
                            if(fg3SupplyfileCategoryList==null||fg3SupplyfileCategoryList.size()==0){
                                //获取phid
                                JSONArray phidsJA = null;
                                phidsJA = i8Request.GetPhids("phid","fg3_supplyfile_category",1+"");
                                if(phidsJA!=null&&phidsJA.size()>0) {
                                    String phid = phidsJA.getString(0);
                                    Fg3SupplyfileCategory fg3SupplyfileCategory = Fg3SupplyfileCategory.builder()
                                            .phid(phid).entId(ent_id).orgId(org_id)
                                            .categoryId(suppclassId).creator("0").editor("0").ngInsertDt(now).ngUpdateDt(now).ngRecordVer("1").phidSupplyrank("0")
                                            .build();
                                    fg3SupplyfileCategoryMapper.insert(fg3SupplyfileCategory);
                                }

                            }else{
                                /*
                                Fg3SupplyfileCategory fg3SupplyfileCategory = fg3SupplyfileCategoryList.get(0);
                                UpdateWrapper updateWrapper = new UpdateWrapper();
                                updateWrapper.eq("phid", fg3SupplyfileCategory.getPhid());
                                updateWrapper.set("category_id",suppclassId);
                                fg3SupplyfileCategoryMapper.update(null,updateWrapper);
                                 */
                            }
                        }
                    }

                    //处理结算银行信息
                    List<SupplyBankInfo> bankInfoList = supplyModel.getBankInfoList();
                    if(bankInfoList!=null&&bankInfoList.size()>0){
                        int len = bankInfoList.size();
                        JSONArray phidsJA = null;
                        if(len>0){
                            phidsJA = i8Request.GetPhids("phid","fg3_unitaccount",len+"");
                            if(phidsJA==null||phidsJA.size()==0) {
                                //未获取到主键信息
                            }else{
                                for(int i=0;i<len;i++){
                                    SupplyBankInfo supplyBankInfo = bankInfoList.get(i);
                                    String bankno = supplyBankInfo.getBankno();
                                    //查询联行号是否存在
                                    String bankId = "0";
                                    if(!StringUtils.isEmpty(bankno)){
                                        QueryWrapper<FgBank> queryBankIsExistWrapper = new QueryWrapper<>();
                                        queryBankIsExistWrapper.eq("bankno",bankno);
                                        List<FgBank> fgBankList = fgBankMapper.selectList(queryBankIsExistWrapper);
                                        if(fgBankList==null||fgBankList.size()==0){
                                            bankno = "";
                                        }else{
                                            FgBank fgBank = fgBankList.get(0);
                                            bankId = fgBank.getPhid();
                                        }
                                    }
                                    String saccount = supplyBankInfo.getSaccount();
                                    String isdef = supplyBankInfo.getIsdef();
                                    String account_name = supplyBankInfo.getAccountName();
                                    isdef = StringUtils.isEmpty(isdef)?"0":isdef;
                                    isdef = "1".equals(isdef)?"1":"0";
                                    SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String datestr = bartDateFormat.format(new Date());
                                    Date ng_insert_dt = bartDateFormat.parse(datestr);
                                    //查询该结算银行是否存在
                                    QueryWrapper<Fg3Unitaccount> queryUnitAccountIsExistWrapper = new QueryWrapper<>();
                                    queryUnitAccountIsExistWrapper.eq("saccount",saccount)
                                            .eq("ent_id",ent_id)
                                            .eq("acctype","supply");

                                    List<Fg3Unitaccount> fg3UnitaccountList = fg3UnitaccountMapper.selectList(queryUnitAccountIsExistWrapper);
                                    if(fg3UnitaccountList==null||fg3UnitaccountList.size()==0)
                                    {
                                        String phid = phidsJA.getString(i);
                                        //新增
                                        Fg3Unitaccount fg3Unitaccount = Fg3Unitaccount.builder()
                                                .phid(phid).entId(ent_id)
                                                .orgId(org_id)
                                                .bankId(bankId).saccount(saccount).isdef(isdef).acctype("supply").creator("0").
                                                editor("0").ngInsertDt(ng_insert_dt).ngUpdateDt(ng_insert_dt).ngRecordVer("1").
                                                remarks("").accountName(account_name).provinceId("0").cityId("0").regionId("0")
                                                .build();
                                        fg3UnitaccountMapper.insert(fg3Unitaccount);
                                    }else{
                                        Fg3Unitaccount fg3Unitaccount = fg3UnitaccountList.get(0);
                                        //更新
                                        UpdateWrapper<Fg3Unitaccount> updateWrapper = new UpdateWrapper<>();
                                        updateWrapper.set("account_name",account_name);
                                        updateWrapper.set("isdef",isdef).set("saccount",saccount).set("bank_id",bankId).
                                                eq("phid",fg3Unitaccount.getPhid());
                                        fg3UnitaccountMapper.update(null,updateWrapper);
                                    }
                                    //只保留当前银行账户为默认银行  其他银行账户设置为非默认
                                    UpdateWrapper<Fg3Unitaccount> updateWrapper = new UpdateWrapper<>();
                                    updateWrapper.set("isdef","0").
                                            eq("ent_id",ent_id).and(item->item.ne("saccount",saccount));
                                    fg3UnitaccountMapper.update(null,updateWrapper);

                                    //更新默认银行信息
                                    if("1".equals(isdef)){
                                        UpdateWrapper<Fg3Supplysettleinfo> updateSettleInfoWrapper = new UpdateWrapper<>();
                                        updateSettleInfoWrapper.set("account_name",account_name);
                                        updateSettleInfoWrapper.set("accountno",saccount);
                                        updateSettleInfoWrapper.set("bank_id",bankId)
                                                .eq("ent_id",ent_id).eq("org_id",org_id);
                                        fg3SupplysettleinfoMapper.update(null,updateSettleInfoWrapper);
                                    }

                                }
                            }
                        }

                    }

                    codeMsg.code = "S";
                    codeMsg.msg = "新增成功.";
                } else {
                    codeMsg.code = "E";
                    codeMsg.msg = "同步失败:"+i8rvJson.getString("Msg");
                }
            }else{
                //执行更新
                Date now = new Date();
                SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String nowTime = bartDateFormat.format(now);
                UpdateWrapper updateEnterpriseWrapper = new UpdateWrapper();
                updateEnterpriseWrapper.eq("compno", supplyModel.compno);
                updateEnterpriseWrapper.set("compname",supplyModel.compname);
                updateEnterpriseWrapper.set("ng_update_dt",now);
                updateEnterpriseWrapper.set("auditflg","1");
                fg3EnterpriseMapper.update(null,updateEnterpriseWrapper);

                Fg3Enterprise fg3Enterprise = fg3EnterpriseList.get(0);

                QueryWrapper<Fg3Supplyfile> fg3SupplyfileQueryWrapper = new QueryWrapper<>();
                fg3SupplyfileQueryWrapper.eq("ent_id",fg3Enterprise.getPhid());
                List<Fg3Supplyfile> fg3SupplyfileList = fg3SupplyfileMapper.selectList(fg3SupplyfileQueryWrapper);
                if(fg3SupplyfileList!=null&&fg3SupplyfileList.size()>0){
                    //更新
                    /*
                    Fg3Supplyfile fg3Supplyfile = fg3SupplyfileList.get(0);
                    UpdateWrapper<Fg3Supplyfile> fg3SupplyfileUpdateWrapper = new UpdateWrapper<>();
                    fg3SupplyfileUpdateWrapper.set("accstop","")
                            .eq("phid",fg3Supplyfile.getPhid());
                    fg3SupplyfileMapper.update(null,fg3SupplyfileUpdateWrapper);
                     */
                }else{
                    //引入
                    List<NameValuePair> urlParameters = new ArrayList<>();
                    urlParameters.add(new BasicNameValuePair("entid", fg3Enterprise.getPhid()));
                    urlParameters.add(new BasicNameValuePair("orgid", "0"));
                    urlParameters.add(new BasicNameValuePair("propertyno", fg3Enterprise.getFromtype()));
                    urlParameters.add(new BasicNameValuePair("types", "1000"));
                    String i8rv = i8Request.PostFormSync("/DMC/Enterprise/SupplyFile/SaveSupplyFileByImportEnt", urlParameters);
                }

                List<String> supplyTypes = supplyModel.getSuppclass();
                if(supplyTypes!=null&&supplyTypes.size()>0){
                    int types = supplyTypes.size();
                    for(int i=0;i<types;i++){
                        String suppclassId = supplyTypes.get(i);
                        if(i==0){
                            //处理供应商主类型
                            UpdateWrapper updateWrapper = new UpdateWrapper();
                            updateWrapper.eq("ent_id", fg3Enterprise.getPhid());
                            updateWrapper.set("suppclass_id",suppclassId);
                            updateWrapper.set("auditflg","1");
                            fg3SupplyfileMapper.update(null,updateWrapper);
                        }
                        //处理供应商分类的问题
                        QueryWrapper<Fg3SupplyfileCategory> fg3SupplyfileCategoryQueryWrapper = new QueryWrapper<>();
                        fg3SupplyfileCategoryQueryWrapper.eq("ent_id",fg3Enterprise.getPhid()).eq("category_id",suppclassId);
                        List<Fg3SupplyfileCategory> fg3SupplyfileCategoryList = fg3SupplyfileCategoryMapper.selectList(fg3SupplyfileCategoryQueryWrapper);
                        if(fg3SupplyfileCategoryList==null||fg3SupplyfileCategoryList.size()==0){
                            //获取phid
                            JSONArray phidsJA = null;
                            phidsJA = i8Request.GetPhids("phid","fg3_supplyfile_category",1+"");
                            if(phidsJA!=null&&phidsJA.size()>0) {
                                String phid = phidsJA.getString(0);
                                Fg3SupplyfileCategory fg3SupplyfileCategory = Fg3SupplyfileCategory.builder()
                                        .phid(phid).entId(fg3Enterprise.getPhid()).orgId(fg3Enterprise.getFromorgId())
                                        .categoryId(suppclassId).creator("0").editor("0").ngInsertDt(now).ngUpdateDt(now).ngRecordVer("1").phidSupplyrank("0")
                                        .build();
                                fg3SupplyfileCategoryMapper.insert(fg3SupplyfileCategory);
                            }

                        }else{
                                /*
                                Fg3SupplyfileCategory fg3SupplyfileCategory = fg3SupplyfileCategoryList.get(0);
                                UpdateWrapper updateWrapper = new UpdateWrapper();
                                updateWrapper.eq("phid", fg3SupplyfileCategory.getPhid());
                                updateWrapper.set("category_id",suppclassId);
                                fg3SupplyfileCategoryMapper.update(null,updateWrapper);
                                 */
                        }
                    }
                }

                //处理结算银行信息
                List<SupplyBankInfo> bankInfoList = supplyModel.getBankInfoList();
                if(bankInfoList!=null&&bankInfoList.size()>0){
                    int len = bankInfoList.size();
                    JSONArray phidsJA = null;
                    if(len>0){
                        phidsJA = i8Request.GetPhids("phid","fg3_unitaccount",len+"");
                        if(phidsJA==null||phidsJA.size()==0) {
                            //未获取到主键信息
                        }else{
                            for(int i=0;i<len;i++){
                                SupplyBankInfo supplyBankInfo = bankInfoList.get(i);
                                String bankno = supplyBankInfo.getBankno();
                                //查询联行号是否存在
                                String bankId = "0";
                                if(!StringUtils.isEmpty(bankno)){
                                    QueryWrapper<FgBank> queryBankIsExistWrapper = new QueryWrapper<>();
                                    queryBankIsExistWrapper.eq("bankno",bankno);
                                    List<FgBank> fgBankList = fgBankMapper.selectList(queryBankIsExistWrapper);
                                    if(fgBankList==null||fgBankList.size()==0){
                                        bankno = "";
                                    }else{
                                        FgBank fgBank = fgBankList.get(0);
                                        bankId = fgBank.getPhid();
                                    }
                                }
                                String saccount = supplyBankInfo.getSaccount();
                                String isdef = supplyBankInfo.getIsdef();
                                String account_name = supplyBankInfo.getAccountName();
                                isdef = StringUtils.isEmpty(isdef)?"0":isdef;
                                isdef = "1".equals(isdef)?"1":"0";
                                String datestr = bartDateFormat.format(new Date());
                                Date ng_insert_dt = bartDateFormat.parse(datestr);
                                //查询该结算银行是否存在
                                QueryWrapper<Fg3Unitaccount> queryUnitAccountIsExistWrapper = new QueryWrapper<>();
                                queryUnitAccountIsExistWrapper.eq("saccount",saccount)
                                        .eq("ent_id",fg3Enterprise.getPhid())
                                        .eq("acctype","supply");

                                List<Fg3Unitaccount> fg3UnitaccountList = fg3UnitaccountMapper.selectList(queryUnitAccountIsExistWrapper);
                                if(fg3UnitaccountList==null||fg3UnitaccountList.size()==0)
                                {
                                    String phid = phidsJA.getString(i);
                                    //新增
                                    Fg3Unitaccount fg3Unitaccount = Fg3Unitaccount.builder()
                                            .phid(phid).entId(fg3Enterprise.getPhid())
                                            .orgId(fg3Enterprise.getFromorgId())
                                            .bankId(bankId).saccount(saccount).isdef(isdef).acctype("supply").creator("0").
                                            editor("0").ngInsertDt(ng_insert_dt).ngUpdateDt(ng_insert_dt).ngRecordVer("1").
                                            remarks("").accountName(account_name).provinceId("0").cityId("0").regionId("0")
                                            .build();
                                    fg3UnitaccountMapper.insert(fg3Unitaccount);
                                }else{
                                    Fg3Unitaccount fg3Unitaccount = fg3UnitaccountList.get(0);
                                    //更新
                                    UpdateWrapper<Fg3Unitaccount> updateWrapper = new UpdateWrapper<>();
                                    updateWrapper.set("account_name",account_name);
                                    updateWrapper.set("isdef",isdef).set("saccount",saccount).set("bank_id",bankId).
                                            eq("phid",fg3Unitaccount.getPhid());
                                    fg3UnitaccountMapper.update(null,updateWrapper);
                                }

                                //只保留当前银行账户为默认银行  其他银行账户设置为非默认
                                UpdateWrapper<Fg3Unitaccount> updateWrapper = new UpdateWrapper<>();
                                updateWrapper.set("isdef","0").
                                        eq("ent_id",fg3Enterprise.getPhid()).and(item->item.ne("saccount",saccount));
                                fg3UnitaccountMapper.update(null,updateWrapper);

                                //更新默认银行信息
                                if("1".equals(isdef)){
                                    UpdateWrapper<Fg3Supplysettleinfo> updateSettleInfoWrapper = new UpdateWrapper<>();
                                    updateSettleInfoWrapper.set("account_name",account_name);
                                    updateSettleInfoWrapper.set("accountno",saccount);
                                    updateSettleInfoWrapper.set("bank_id",bankId)
                                            .eq("ent_id",fg3Enterprise.getPhid()).eq("org_id",fg3Enterprise.getFromorgId());
                                    fg3SupplysettleinfoMapper.update(null,updateSettleInfoWrapper);
                                }

                            }
                        }
                    }

                }

                codeMsg.code = "S";
                codeMsg.msg = "更新成功.";
            }

        }catch (Exception ex)
        {
            codeMsg.code = "E";
            codeMsg.msg = "出现异常:"+ex.getMessage();
        }
        return  codeMsg;
    }


    public StatusMsg Message(String data) {
        StatusMsg statusMsg = new StatusMsg();
        try {
            uipLog.info("supplymessage", "供应商消息",data);
            JSONObject dataJO = JSONObject.parseObject(data);
            String supplyid = dataJO.getString("id");
            Date now = new Date();
            //存入中间表
            String phid = GetNewPhidUtils.getPhid();
            SecDevMdmSupply secDevMdmSupply = SecDevMdmSupply.builder()
                    .phid(phid).supplyid(supplyid).ngInsertDt(now)
                    .build();
            secDevMdmSupplyMapper.insert(secDevMdmSupply);
            //调用供应商获取数据接口
            String postUrl =ckUrl +"/supplier/supplierInfo/provideId?id="+supplyid;
            Header[] headers = new Header[]{
                    new BasicHeader("Content-Type","application/json")
            };
            String rtnMsg = HttpHelper.Get(postUrl,headers);
            if(!StringUtils.isEmpty(rtnMsg)){
                JSONObject supplyJO = JSONObject.parseObject(rtnMsg);
                if("200".equals(supplyJO.getString("code"))){
                    JSONObject dataJORtn = supplyJO.getJSONObject("data");
                    List<SuppClass> suppClassList = suppClassMapper.selectList(null);
                    boolean flag = SyncCkSupplyByDataJO(dataJORtn,suppClassList);
                    //同步数据成功之后 标记中间表数据
                    if(flag){
                        now = new Date();
                        UpdateWrapper updateWrapper = new UpdateWrapper();
                        updateWrapper.eq("phid", phid);
                        updateWrapper.set("sync_flg","1");
                        updateWrapper.set("sync_time",now);
                        secDevMdmSupplyMapper.update(null,updateWrapper);
                    }
                }
            }

            statusMsg.message = "接收成功";
            statusMsg.status = "success";
        }catch (Exception ex){
            statusMsg.message = "接收异常";
            statusMsg.status = "error";
        }
        return statusMsg;
    }


    public void deleteData() {
        try
        {
            uipLog.info("deletesupply", "同步供应商","开始执行");
            //查询重复的供应商
            List<Map<String,Object>> fg3SupplyfileList =  fg3SupplyfileMapper.getFg3Supplyfile();
            if(fg3SupplyfileList!=null&&fg3SupplyfileList.size()>0){
                int count = fg3SupplyfileList.size();
                uipLog.info("deletesupply", "同步供应商","总条数:"+count);
                for(int i=0;i<count;i++){
                    Map<String,Object> fg3Supplyfile = fg3SupplyfileList.get(i);
                    String phid = fg3Supplyfile.get("phid").toString();
                    String entid = fg3Supplyfile.get("ent_id").toString();

                    UpdateWrapper<Fg3Supplyfile> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("auditflg","0").eq("phid",phid);
                    fg3SupplyfileMapper.update(null,updateWrapper);

                    List<NameValuePair> urlParameters = new ArrayList<>();
                    urlParameters.add(new BasicNameValuePair("id", phid));
                    urlParameters.add(new BasicNameValuePair("entid", entid));
                    urlParameters.add(new BasicNameValuePair("phidcu", ""));
                    urlParameters.add(new BasicNameValuePair("phidorg", ""));
                    String i8rv = i8Request.PostFormSync("/DMC/Enterprise/SupplyFile/Delete", urlParameters);
                    uipLog.info("deletesupply", "同步供应商","phid:"+phid+";endid:"+entid+";同步返回:"+i8rv);
                }
            }
        }catch (Exception ex){
            uipLog.error("deletesupply", "同步供应商","同步异常:"+ex.getMessage());
        }
    }
}
